<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />

    <div v-if="isExtractVideo" style="margin-bottom: 15px;">
      <el-input
        placeholder="Please Input Link"
        v-model="ExtractVideo"
        class="input-with-select"
        style="width: 600px;"
      >
        <el-button slot="append" @click="ExtractVideoFn">Extract</el-button>
      </el-input>
      <div style="margin-top: 5px;">
        <a :href="videoUrl" target="_blank">Navigate to a new page Download</a>
        <el-button
          type="primary"
          slot="append"
          @click="videoUrlFn"
          :disabled="!videoUrl"
          >Last Page Download</el-button
        >
      </div>
    </div>

    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    ></r-table>

    <r-form
      labelWidth="160px"
      :isHandle="true"
      :formRules="formRules2"
      :formCols="formCols2"
      :formHandle="formHandle2"
      :formData="formData2"
      ref="elForm2"
      :inline="false"
      dialogWidth="870px"
    >
      <!-- 点击编辑按钮出现的Template，里面的站点地址 -->
      <!-- 省 -->
      <div class="zhandiandiz" v-if="isshowss">
        <span>省/市/区/街</span>
        <el-select
          v-model="sValue"
          placeholder="Please Select省份"
          @change="sZhandiandizhi($event)"
          class="szddz"
        >
          <el-option
            v-for="item in sOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 市 -->
        <el-select
          v-model="cValue"
          placeholder="Please Select城市"
          @change="cZhandiandizhi($event)"
          class="czddz"
        >
          <el-option
            v-for="item in cOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 区 -->
        <el-select
          v-model="qValue"
          placeholder="Please Select区/县"
          @change="qZhandiandizhi($event)"
          class="qzddz"
        >
          <el-option
            v-for="(item, index) in qOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <!-- 街 -->
        <el-select
          v-model="jValue"
          placeholder="Please Select街道"
          @change="jZhandiandizhi($event)"
          class="jzddz"
        >
          <el-option
            v-for="(item, index) in jOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>

      <!-- 点击编辑按钮出现的Template，里面的地图 -->
      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="
            border: 1px solid #c0c0c0;
            width: 150px;
            height: auto;
            display: none;
          "
        ></div>
        <p>
          Click on the map to confirm the coordinates：
          <!-- *可以Pass点击地图，快速找到站点地址 -->
        </p>
        <p>Longitude：{{ formData2.lng }} ；Latitude：{{ formData2.lat }}</p>
        <div id="l-map"></div>
      </div>
    </r-form>

    <!-- ImportBattery Swap Records按钮的Template -->
    <Abnormal ref="Abnormal"></Abnormal>
    <!-- Import异常Record按钮的Template -->
    <Abnormal_record ref="Abnormal_record"></Abnormal_record>
    <!-- ImportEmployDetails按钮的Template -->
    <useDetailDialog
      :visible.sync="warehouse_gate_data.show"
      :useDetail="useDetail"
      :res="warehouse_gate_data"
      v-if="warehouse_gate_data.show"
      v-on:warehouse_gate_dall="warehouse_gate_dall"
    ></useDetailDialog>
  </div>
</template>
<script>
import baidumap from "../js/baidumap";
// import warehouse_gate from "./cus/warehouse_gate";
import Abnormal from "./cus/Abnormal";
import Abnormal_record from "./cus/Abnormal_record";
import useDetailDialog from "./cus/useDetailDialog.vue";
import axios from "axios";
export default {
  components: {
    // warehouse_gate,
    Abnormal_record,
    Abnormal,
    useDetailDialog
  },
  data() {
    //编辑按钮 出现的编辑页面的行列方法
    var checkAge = (rule, value, callback) => {
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("Please Enter a numeric value"));
        } else {
          if (value < 0) {
            callback(new Error("Can't be less than 0"));
          } else if (value === 0) {
            callback(new Error("It cannot be equal to 0"));
          } else if (value > 12) {
            callback(new Error("No more than 12"));
          } else {
            callback();
          }
        }
      }, 200);
    };
    return {
      pt: "116.331398, 39.897445",
      isshowss: false, //Control省市区街显示隐藏
      sValue: "", //编辑页面 站点地址 选项的值(省)
      sLabel: "", //编辑页面 站点地址 选项的键名(省)
      sJingwei: "", //编辑页面 站点地址 选项的经纬度(省)
      sOption: [], //编辑页面 站点地址 Data源(省)
      cValue: "", //编辑页面 站点地址 选项的值(市)
      cLabel: "", //编辑页面 站点地址 选项的键名(市)
      cJingwei: "", //编辑页面 站点地址 选项的经纬度(市)
      cOption: [], //编辑页面 站点地址 Data源(市)
      qValue: "", //编辑页面 站点地址 选项的值(区)
      qLabel: "", //编辑页面 站点地址 选项的键名(区)
      qJingwei: "", //编辑页面 站点地址 选项的经纬度(区)
      qOption: [], //编辑页面 站点地址 Data源(区)
      jValue: "", //编辑页面 站点地址 选项的值(街道)
      jLabel: "", //编辑页面 站点地址 选项的键名(街道)
      jJingwei: "", //编辑页面 站点地址 选项的经纬度(街道)
      jOption: [], //编辑页面 站点地址 Data源(街道)
      userType: "", //反映是Agent还是Operator
      visible: false,
      useDetail: {
        extend: {},
        anomalousEvent: {},
        main: {},
        engaged: []
      },

      baiduMap: null, //Control地图
      // Control查看仓门按钮Template的显示隐藏
      warehouse_gate_data: {
        id: "",
        show: false
      },
      searchData: {
        deviceNo: "",
        operatorId: "",
        agentId: "",
        deviceStatus: "",
        deviceType: 1
        // siteId: '',
      },
      // Search框
      searchForm: [
        {
          type: "input",
          prop: "deviceNo",
          placeholder: "Device Number",
          width: 250
        },
        // {
        //   type: 'select',
        //   prop: 'siteId',
        //   placeholder: '铺设站点',
        //   width: 150,
        //   options: []
        // },
        // {
        //   type: "select",
        //   prop: "operatorId",
        //   placeholder: "Operator",
        //   options: [],
        //   // width: 150,

        //   isShow: () => {
        //     return sessionStorage.role == "platform" ? true : false;
        //   }
        // },
        {
          type: "select",
          prop: "agentId",
          placeholder: "Agent ID",
          options: [],
          width: 220,
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        // 设备Status：1：（Online）运行中 2: Offline 3: 设备故障
        {
          type: "select",
          prop: "deviceStatus",
          placeholder: "Device Status",
          width: 250,
          options: [
            {
              label: "Online",
              value: 1
            },
            {
              label: "Offline",
              value: 2
            },
            {
              label: "Malfunction",
              value: 3
            }
          ]
        }
        // {
        //   type: 'input',
        //   prop: 'name',
        //   placeholder: 'Maintenance Personnel',
        //	 width: 150
        // },
      ],

      tableHandles: [
        // {
        //   label: "关联广告合集",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        // {
        //   label: "关联Package",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        {
          label: "Add Device",
          type: "primary",
          plain: true,
          disabled: sessionStorage.role == "operator" ? false : true,
          handle: e => {
            this.formData2.id = null;
            this.formData2.lat = 22.977337;
            this.formData2.lng = 113.303703;
            if (this.userType == "Agent") {
              this.isshowss = true;
            } else {
              this.isshowss = false;
            }

            this.elFormVisible("", "elForm2").then(res => {
              this.map();
            });
          }
        }
        // {
        //   label: "ExportData",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // }
      ],
      tableData: [],
      tableCols: [
        {
          label: "Device Number",
          prop: "deviceNo",
          click: e => {
            this.openOperation();
          }
        },
        {
          label: "QR Code",
          type: "image",
          width: 100,
          prop: "qrCode"
        },
        {
          label: "Device Name",
          prop: "deviceName"
        },
        {
          label: "Business Status",
          prop: "distStatus",
          formatter: e => {
            if (e.distStatus == 0) {
              return "Not Set";
            } else if (e.distStatus == 1) {
              return "Have Set";
            } else {
              return "--";
            }
          },
          itemClass: e =>
            e.distStatus == 0 ? "danger" : e.distStatus == 1 ? "success" : ""
        },
        {
          label: "Electric Changing Cabinet Package",
          prop: "mealExchangeList", // mealExchangeList{id,mealName}
          width: 100,
          isShow: e => this.userType == "Agent",
          formatter: e => {
            let text = "";
            e.mealExchangeList.forEach(i => {
              text = text + "," + i.mealName;
            });
            let reg = new RegExp(","); // 第二个参数不加'g'，仅删除字符串里第一个","
            text = text.replace(reg, "");
            return text;
          }
        },
        {
          label: "Device Signal",
          prop: "signalValue"
        },
        // {
        //   label: "Operator",
        //   prop: "operatorName"
        // },
        {
          label: "Agent",
          prop: "agentName"
        },
        {
          label: "Maintenance Personnel",
          prop: "merName"
        },
        // {
        //   label: "广告合集",
        //   prop: "advertList",
        // },
        {
          label: "coulombmeter",
          prop: "usedElectric",
          formatter: e => (e.usedElectric ? e.usedElectric + "/kwh" : "--")
        },
        {
          label: "Device Power",
          prop: "power",
          formatter: e => (e.power ? e.power + "W" : "--")
        },
        {
          label: "Prohibited stock quantity",
          prop: "disableNum",
          formatter: e => (e.disableNum ? e.disableNum + "individual" : "--")
        },
        // {
        //   label: "Voltage表",
        //   prop: "voltage",
        //   formatter: e => e.voltage ? e.voltage + 'V' : '0V'
        // },
        // {
        //   label: "电流表",
        //   prop: "electricity",
        //   formatter: e => e.electricity ? e.electricity + 'mA' : '0mA'
        // },

        {
          label: "Operation Status",
          prop: "deviceStatus",
          formatter: e => {
            if (e.deviceStatus == 1) {
              return "Online";
            } else if (e.deviceStatus == 2) {
              return "Offline";
            } else if (e.deviceStatus == 3) {
              return "Malfunction";
            } else if (e.deviceStatus == 0) {
              return "-";
            }
          }
        },
        {
          label: "Forbidden",
          prop: "useStatus",
          type: "tag",
          formatter: e =>
            e.useStatus == 2 ? "Forbidden" : e.useStatus == 1 ? "Enable" : "--",
          theme: e => (e.useStatus == 2 ? "warning" : "primary")
        },
        // {
        //   label: "启用Status",
        //   type: "switch",
        //   prop: "useStatus",
        //   values: [1, 2],
        //   change: (row) => this.changestate(row),
        // },
        {
          label: "Operations",
          type: "button",
          width: 220,
          btnList: [
            {
              label: "Device Details",
              type: "text",
              handle: async row => {
                // this.$message({
                //   type: "error",
                //   message: "Please Add Device"
                // });
                this.warehouse_gate_data.id = row.id;
                this.warehouse_gate_data.show = true;
                // console.log("row----", row);
                const res = await this.apis.cabinet_detailList(row.id, "1");
                const data = res.data.extend;
                this.useDetail.extend = res.data.extend;
                this.useDetail.engaged = data.engaged;
                this.useDetail.main = res.data.main;
                this.useDetail.anomalousEvent = res.data.anomalousEvent;
                this.visible = true;
              }
            },

            {
              label: "Abnormal Records",
              type: "text",
              handle: row => {
                this.$refs.Abnormal_record.show_fun(row);
              }
            },
            {
              label: "Forbidden",
              type: "text",
              handle: async row => {
                let res = await this.apis.device_updata({
                  id: row.id,
                  useStatus: 2
                });
                this.$message({
                  type: res.code == 200 ? "success" : "error",
                  message: res.msg
                });
                this.init();
              },
              isShow: row => {
                return row.useStatus == 1 ? true : false;
              }
            },
            {
              label: "Enable",
              type: "text",
              handle: async row => {
                let res = await this.apis.device_updata({
                  id: row.id,
                  useStatus: 1
                });
                this.$message({
                  type: res.code == 200 ? "success" : "error",
                  message: res.msg
                });
                this.init();
              },
              isShow: row => {
                return row.useStatus == 2 ? true : false;
              }
            },
            {
              label: "Edit",
              type: "text",
              handle: row => {
                this.isshowss = false;
                this.add(row);
              }
            },
            {
              label: "QR Code Send",
              type: "text",
              handle: async row => {
                console.log(22, row.deviceNo, row);
                let res = await this.apis.deviceSetQrCode(row.deviceNo);
                this.$message({
                  type: res.code == 200 ? "success" : "error",
                  message: res.msg
                });
              }
            },
            {
              label: "Battery Swap Records",
              type: "text",
              handle: async row => {
                this.$refs.Abnormal.show_fun(row);
                // this.$message({
                //   type: "error",
                //   message: "Please Add Device"
                // });
              }
            }
            // {
            //   label: "Delete",
            //   type: "text",
            //   handle: async (row) => {
            //     this.$confirm("确定要删除吗?", "Hint", {
            //       confirmButtonText: "Confirm",
            //       cancelButtonText: "Cancel",
            //       type: "warning",
            //     })
            //       .then(async () => {
            //         var res = await this.apis.device_del({
            //           id: row.id,
            //         });
            //         this.$message({
            //           type: "success",
            //           message: "删除Success!",
            //         });
            //         this.init();
            //       })
            //       .catch(() => { });
            //   },
            // },
          ]
        }
      ],

      formData: {
        name: "",
        money: "",
        giftMoney: "",
        status: ""
      },
      formCols: [
        { type: "input", label: "Package Name", width: 350, prop: "name" },
        {
          type: "input",
          label: "PackageMoney",
          width: 350,
          prop: "money"
          // remark: "元"
        },
        {
          type: "input",
          label: "Gift Amount",
          width: 350,
          prop: "giftMoney"
          // remark: "元"
        },
        { type: "switch", label: "Online/Offline", width: 350, prop: "status" }
      ],
      formRules: {
        name: [
          {
            required: true,
            message: "Please InputPackage Name",
            trigger: "blur"
          }
        ],
        money: [
          {
            required: true,
            message: "Please InputPackageMoney",
            trigger: "blur"
          }
        ],
        giftMoney: [
          {
            required: true,
            message: "Please InputPackageMoney",
            trigger: "blur"
          }
        ]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      isId: false,
      ExtractVideo: "",
      videoUrl: "",
      isExtractVideo: false,
      clickTimer: null,
      waitTime: 1000, // 该时间间隔内点击才算连续点击（单位：ms）
      lastTime: 0,
      clickCount: 0, // 连续点击Frequency
      // 编辑按钮form表单的变量
      formData2: {
        deviceNo: "",
        deviceName: "",
        address: "",
        // siteId: "",
        // name: '',
        id: "",
        lng: "",
        lat: "",
        operatorId: "",
        agentId: "",
        merId: "",
        // boxNum: '',
        cols: "",
        rows: "",
        sim: "",
        deviceType: "1"

        // mealName: '',
      },

      // 编辑按钮form表单的Data源
      formCols2: [
        {
          type: "input",
          label: "Electric changing cabinet Id",
          placeholder: "Please Enter",
          width: 350,
          prop: "id",
          options: [],
          isShow: e => {
            return sessionStorage.role == "operator" ? false : true;
          },
          isDisabled: e => true
        },
        {
          type: "input",
          label: "Device Number",
          placeholder: "Please Enter",
          width: 350,
          prop: "deviceNo",
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          type: "input",
          label: "Device Name",
          placeholder: "Please Enter",
          width: 350,
          prop: "deviceName"
        },
        // { type: 'input', label: '格子数量', placeholder: 'Please Enter', width: 350, prop: 'boxNum' },
        {
          type: "number",
          label: "Cabinet Door Number",
          placeholder: "Please Enter",
          width: 350,
          prop: "boxNumber",
          // remark: "仓",
          // isDisabled: (e) => (e.id ? true : false),
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        // {
        //   type: "input",
        //   label: "列数",
        //   placeholder: "Please Enter",
        //   width: 350,
        //   prop: "cols",
        //   // isDisabled: (e) => (e.id ? true : false),
        //   isShow: () => {
        //     return sessionStorage.role == "operator" ? true : false;
        //   },
        // },
        // {
        //   type: "input",
        //   label: "行数",
        //   placeholder: "Please Enter",
        //   width: 350,
        //   prop: "rows",
        //   isShow: () => {
        //     return sessionStorage.role == "operator" ? true : false;
        //   },
        // },
        {
          type: "input",
          label: "sim Number",
          placeholder: "Please Enter",
          width: 350,
          prop: "sim",
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        // { type: "select", label: "设备类型", placeholder: 'Please Enter', width: 350, prop: "deviceType",options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'Charging Cabinet',value:'3'},
        //   ] },
        // {
        //   type: "select",
        //   label: "选择站点",
        //   placeholder: "Please Enter",
        //   width: 350,
        //   prop: "siteId",
        //   options: [],
        //   isShow: () => {
        //     return sessionStorage.role == "operator" ? false : true;
        //   },
        // },
        // {
        //   type: "select",
        //   label: "选择Operator",
        //   placeholder: "Please Enter",
        //   width: 350,
        //   prop: "operatorId",
        //   options: [],
        //   isShow: () => {
        //     return sessionStorage.role == "operator" ? false : true;
        //   },
        // },
        {
          type: "select",
          label: "Select Agent",
          placeholder: "Please Enter",
          width: 350,
          prop: "agentId",
          options: [],
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        // {
        //   type: "select",
        //   label: "Select Maintenance",
        //   placeholder: "Please Enter",
        //   width: 350,
        //   prop: "merId",
        //   options: [],
        //   isShow: () => {
        //     return sessionStorage.role == "operator" ? false : true;
        //   },
        // },

        {
          //只有Add才有，编辑没有
          type: "",
          isShow: () => {
            return !this.formData2.id && this.userType == "Agent"
              ? true
              : false;
          }
        },
        {
          type: "input",
          id: "suggestId",
          label: "Device Address",
          placeholder:
            "The device address can be obtained or entered by clicking on the map",
          width: 350,
          prop: "address",
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          type: "slot",
          name: "slot3",
          label: "",
          prop: "lng",
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        }
      ],
      // 编辑按钮中的编辑页面 的输入框提示信息
      formRules2: {
        deviceNo: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        // boxNum: [{ required: true, message: 'Please Enter', trigger: 'blur' }, { validator: checkAge, trigger: 'blur' }],
        // cols: [
        //   { required: true, message: "Please Enter", trigger: "blur" },
        //   { validator: checkAge, trigger: "blur" },
        // ],
        // rows: [
        //   { required: true, message: "Please Enter", trigger: "blur" },
        //   { validator: checkAge, trigger: "blur" },
        // ],
        boxNumber: [
          { required: true, message: "Please Enter", trigger: "blur" },
          { validator: checkAge, trigger: "blur" }
        ],
        sim: [{ required: true, message: "Please Enter", trigger: "blur" }],
        // deviceType: [{ required: true, message: "Please Select", trigger: "blur" }],
        // siteId: [{ required: true, message: "Please Input站点", trigger: "blur" }],

        // operatorId: [{ required: true, message: "Please SelectOperator", trigger: "blur" }],
        agentId: [
          { required: true, message: "Please SelectAgent", trigger: "blur" }
        ],
        merId: [
          {
            required: true,
            message: "Please SelectMaintenance",
            trigger: "blur"
          }
        ],
        lng: [
          {
            required: true,
            message: "Click on the map to select latitude and longitude",
            trigger: "blur"
          }
        ],
        address: [
          {
            required: true,
            message: "Please Input Detailed Device Address",
            trigger: "blur"
          }
        ]
      },
      formHandle2: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible("", "elForm2")
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit2()
        }
      ],
      weihuArr: [],
      baiteng: { lat: "", lng: "" },
      tengbai: { lat: "", lng: "" },
      // Search按钮
      searchHandle: [
        {
          label: "Search",
          type: "success",
          plain: true,
          icon: "el-icon-search",
          handle: e => {
            this.zeroFn();
            this.init();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              deviceNo: "",
              operatorId: "",
              agentId: "",
              deviceStatus: "",
              deviceType: 1
            };
            this.zeroFn();
            this.init();
          }
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 }
    };
  },

  mounted() {
    this.init();
    // this.site_list();
    //userType为1是Operator，2是Agent
    if (sessionStorage.getItem("userType") == "1") {
      this.userType = "Operator";
    }
    if (sessionStorage.getItem("userType") == "2") {
      this.userType = "Agent";
    }
    if (sessionStorage.role == "platform") {
      this.operator_list();
    }
    if (sessionStorage.role == "operator") {
      this.agent_list();
      this.maintenancer_list();
    }
    if (sessionStorage.role !== "operator") {
      this.agent_list();
    }
  },
  updated() {
    // 选择省市区街下拉框，编辑页面的站点地址会改变
    if (this.sLabel && !this.cLabel && !this.qLabel && !this.jLabel) {
      this.formData2.address = "";
      this.formData2.address = this.sLabel;
    } else if (this.sLabel && this.cLabel && !this.qLabel && !this.jLabel) {
      this.formData2.address = "";
      this.formData2.address = this.sLabel + this.cLabel;
    } else if (this.sLabel && this.cLabel && this.qLabel && !this.jLabel) {
      this.formData2.address = "";
      this.formData2.address = this.sLabel + this.cLabel + this.qLabel;
    } else if (this.sLabel && this.cLabel && this.qLabel && this.jLabel) {
      this.formData2.address = "";
      this.formData2.address =
        this.sLabel + this.cLabel + this.qLabel + this.jLabel;
    } else {
    }
  },
  watch: {
    // 监听省，如果下拉框的省发生改变，就会发送请求，更新市的Data
    sLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用编辑页面 --站点地址-- 城市（Data） 的方法
        this.czhandianfangfa(this.sLabel, this.sValue);
        // 当重新选择省，市区街和站点地址情况，重新更新
        this.cLabel = "";
        this.qLabel = "";
        this.jLabel = "";
        this.cValue = "";
        this.qValue = "";
        this.jValue = "";
      }
    },
    // 监听市，如果下拉框的市发生改变，就会发送请求，更新区的Data
    cLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用编辑页面 --站点地址-- 区（Data） 的方法
        this.qzhandianfangfa(this.cLabel, this.cValue);
        // 当重新选择市，区街和站点地址情况，重新更新
        this.qLabel = "";
        this.jLabel = "";
        this.qValue = "";
        this.jValue = "";
      }
    },
    // 监听区，如果下拉框的区发生改变，就会发送请求，更新街道的Data
    qLabel(newV, oldV) {
      if (newV !== oldV) {
        // 调用编辑页面 --站点地址-- 街道（Data） 的方法
        this.jzhandianfangfa(this.qLabel, this.qValue);
        // 当重新选择区，街和站点地址情况，重新更新

        this.jLabel = "";
        this.jValue = "";
      }
    },
    // 监听街道，如果下拉框的街道发生改变，就会发送请求，更新街道的Data
    // jValue(newV, oldV) {
    //   if (newV !== oldV) {
    //     console.log(newV, oldV);
    //     // 调用编辑页面 --站点地址-- 街道（Data） 的方法
    //     // this.jzhandianfangfa(this.qLabel, this.qValue)
    //   }
    // },
    "formData2.lng"(newV, oldV) {
      if (newV !== oldV) {
        console.log(newV, oldV, "===============");
      }
    },

    "formData2.address": {
      handler(newVal, oldVal) {
        // console.log(newVal);
        // console.log(oldVal);
      },
      deep: true // 深度监听
    }
  },

  methods: {
    zeroFn() {
      this.tablePage.limit = 10;
      this.tablePage.page = 1;
      this.tablePage.total = 0;
    },
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.device_list(parm);
      if (res) {
        // let key = 'mealName'
        let keys = "name";
        this.tableData = res.rows;
        this.tablePage.total = res.total;
        this.tableData.forEach(item => {
          // 防止Add的属性值为空
          if (item.mealExchangeList) {
            this.weihuArr = item.mealExchangeList;
          } else {
            this.weihuArr = [];
          }
          // 防止Add的属性值为空
          if (item.siteEntity) {
            item[keys] = item.siteEntity.name;
          } else {
            item[keys] = "-";
          }
        });

        // console.log(this.tableData);
      }
      // 编辑页面 站点地址  ---拿到省份(Data)
      const addressRes = await this.apis.allAddressList({});
      if (addressRes.code === 0) {
        var array = new Array();
        addressRes.result.forEach(item => {
          let obj = {
            label: item.name,
            value: item.adcode,
            jingwei: item.center
          };
          this.sOption.push(obj);
          array.push(obj);
        });

        this.formCols2[
          this.labIndex2(this.formCols2, "address")
        ].options = array;
      }
    },
    async elFormSubmit() {
      this.formData.state = this.formData.status == true ? 1 : 2;
      if (this.formData.id) {
        let res = await this.api.packupdate(this.formData);
        if (res) {
          this.formData.id = "";
          this.elFormVisible();
          this.init();
        }
      } else {
        let res = await this.api.packadd(this.formData);
        if (res) {
          this.elFormVisible();
          this.init();
        }
      }
    },

    // 百度地图经纬度转为腾讯地图经纬度
    bdMapToTxMap(lat, lng) {
      console.log("百度地图经纬度", lat, lng);
      let pi = (3.14159265358979324 * 3000.0) / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
      lng = z * Math.cos(theta);
      lat = z * Math.sin(theta);
      this.tengbai.lng = lng;
      this.tengbai.lat = lat;
      console.log("腾讯地图经纬度", this.tengbai.lng, this.tengbai.lat);
    },
    //  腾讯地图转百度地图经纬度
    txMapToBdMap(lng, lat) {
      let x_pi = (3.14159265358979324 * 3000.0) / 180.0;
      let x = lng;
      let y = lat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta) + 0.0065;
      let lats = z * Math.sin(theta) + 0.006;
      this.baiteng.lng = lngs;
      this.baiteng.lat = lats;
    },

    add(row) {
      // this.formData2.id = row.id;
      this.elFormVisible("", "elForm2").then(res => {
        this.txMapToBdMap(row.lng, row.lat);
        this.formData2.lng = this.baiteng.lng;
        this.formData2.lat = this.baiteng.lat;
        this.map().then(res => {
          if (row) {
            Object.keys(this.formData2).forEach(key => {
              this.formData2[key] = row[key];
              this.formData2.lng = this.baiteng.lng;
              this.formData2.lat = this.baiteng.lat;
            });
          }
        });
      });
    },
    // 编辑按钮出现后的编辑页面的  绑定确认按钮的方法
    async elFormSubmit2() {
      this.bdMapToTxMap(this.formData2.lat, this.formData2.lng);
      this.formData2.lng = this.tengbai.lng;
      this.formData2.lat = this.tengbai.lat;
      this.$refs.elForm2.$refs.ruleForm.validate(async valid => {
        if (valid) {
          console.log(valid + "===========");
          if (this.formData2.id) {
            //Edit
            let res;
            if (sessionStorage.role == "operator") {
              res = await this.apis.device_updata(this.formData2);
            } else {
              res = await this.apis.deviceAllocationDevice(this.formData2);
              delete this.formData2.ids;
            }

            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          } else {
            //Add
            let res = await this.apis.device_save(this.formData2);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          }
        }
      });
    },

    //编辑按钮Template中的地图
    map() {
      // 百度地图API功能
      function G(id) {
        return document.getElementById(id);
      }
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder(); //地址解析对象
      var ssss = new BMap.Point(this.formData2.lng, this.formData2.lat); //获取经纬度
      var ac = new BMap.Autocomplete({ input: "suggestId", location: map }); // 建立一个自动完成的对象
      // console.log(111111, ssss);
      map.clearOverlays(); // 清除地图上所有覆盖物
      map.centerAndZoom(ssss, 20); //Setup地图中心点

      map.addOverlay(new BMap.Marker(ssss)); // Add标注
      // 点击地图某一个点  更新经纬度
      map.addEventListener("click", function(e) {
        //点击获取地图的经纬度赋值给全局的经纬度
        that.formData2.lng = e.point.lng;
        that.formData2.lat = e.point.lat;
        var pt = e.point;
        // console.log(2222, e);
        map.clearOverlays(); // 清除地图上所有覆盖物
        // var ssss = new BMap.Point(pt.lng, pt.lat); //获取经纬度
        // map.centerAndZoom(pt, 20); //Setup地图中心点
        map.addOverlay(new BMap.Marker(pt)); // Add标注
        geoc.getLocation(pt, function(rs) {
          that.formData2.address = rs.address; //点击地图拿到详细地址
          var addComp = rs.addressComponents; //点击地图拿到省 市 区 街
          // that.formData.city = addComp.city;
          // console.log(addComp, 332567, rs, pt.lat);
          // that.formData2.lat = pt.lat;
          // that.formData2.lng = pt.lng;
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
      });
      // 选择下拉框的地址触发的事件
      var myValue;
      ac.addEventListener("onconfirm", function(e) {
        // 鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business;
        G("searchResultPanel").innerHTML =
          "onconfirm<br />index = " +
          e.item.index +
          "<br />myValue = " +
          myValue;

        // Pass传入地址，获取经纬度
        geoc.getPoint(myValue, function(point) {
          if (point) {
            that.formData2.lat = point.lat;
            that.formData2.lng = point.lng;
            // that.infoWindowShow = true;
          }
          // console.log(222, point);
        });

        // console.log(56566, e, that.formData2.address);
      });

      map.enableScrollWheelZoom(); //启用滚轮放大缩小，默认禁用
      map.enableContinuousZoom(); //启用地图惯性拖拽，默认禁用
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 10);
      });
    },

    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.formData.status = row["state"] == 1 ? true : false;
      this.formData.id = row.id;
      // if (this.formCols[1].label == '登录密码') {
      //     this.formCols.splice(1, 1)
      // }
      this.elFormVisible();
    },
    //站点列表
    async site_list() {
      const res = await this.apis.site_list({
        pageNum: 1,
        pageSize: 100000
      });

      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "siteId")
      ].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "siteId")
      ].options = options;
    },
    //Operator-列表
    async operator_list() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 100000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "operatorId")
      ].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "operatorId")
      ].options = options;
    },
    //Agent列表
    async agent_list() {
      const res = await this.apis.agent_list({
        pageNum: 1,
        pageSize: 100000
      });
      if (sessionStorage.role !== "operator" && res.rows.length == 0) {
        var list = [
          {
            name: sessionStorage.nickName,
            id: sessionStorage.optUserId
          }
        ];
      } else {
        var list = res.rows || [];
      }
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });
      this.searchForm[
        this.labIndex2(this.searchForm, "agentId")
      ].options = options;
      this.formCols2[
        this.labIndex2(this.formCols2, "agentId")
      ].options = options;
    },
    //Maintenance Personnel List
    async maintenancer_list() {
      const res = await this.apis.maintenancer_list({
        pageNum: 1,
        pageSize: 1000000
      });
      const list = res.rows || [];
      let options = list.map(res => {
        return {
          label: res.userName,
          value: res.id
        };
      });

      // this.formCols2[this.labIndex2(this.formCols2, "merId")].options = options;
    },
    // Device Details按钮
    warehouse_gate_dall() {
      this.warehouse_gate_data.show = false;
    },
    // // 编辑页面 站点地址 的点击方法(省)
    sZhandiandizhi(value) {
      // console.log(value);
      let sObj = {};
      sObj = this.sOption.find(item => {
        //这里的sOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.sLabel = sObj.label; //拿到键名
      this.sOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.sJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.sJingwei.split(",")[0];
      this.formData2.lat = this.sJingwei.split(",")[1];
      this.pt = this.sJingwei;
    },

    // // 编辑页面 站点地址 的点击方法(市)
    cZhandiandizhi(value) {
      // console.log(value);
      let cObj = {};
      cObj = this.cOption.find(item => {
        //这里的cOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.cLabel = cObj.label; //拿到键名
      this.cOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.cJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.cJingwei.split(",")[0];
      this.formData2.lat = this.cJingwei.split(",")[1];
      this.pt = this.cJingwei;
    },
    // // 编辑页面 站点地址 的点击方法(区)
    qZhandiandizhi(value) {
      let qObj = {};
      qObj = this.qOption.find(item => {
        //这里的cOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.qLabel = qObj.label; //拿到键名
      this.qOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.qJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.qJingwei.split(",")[0];
      this.formData2.lat = this.qJingwei.split(",")[1];
      this.pt = this.qJingwei;
    },

    // // 编辑页面 站点地址 的点击方法(街道)
    jZhandiandizhi(value) {
      let jObj = {};
      jObj = this.jOption.find(item => {
        //这里的jOption就是上面遍历的Data源
        return item.value === value; //筛选出匹配Data
      });
      this.jLabel = jObj.label; //拿到键名
      console.log(this.jLabel);
      this.jOption.find(item => {
        //经纬度
        if (item.value === value) {
          this.jJingwei = item.jingwei;
        }
      });
      //拿到后端返回的经纬度，赋值给地图上的经纬度
      this.formData2.lng = this.jJingwei.split(",")[0];
      this.formData2.lat = this.jJingwei.split(",")[1];
      this.pt = this.jJingwei;
    },

    // // 编辑页面地图 ---拿到城市（Data）
    czhandianfangfa(label, value) {
      this.cOption = []; //每次进来先清空城市的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            res.result.forEach(item => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              };
              this.cOption.push(obj);
            });
            console.log(this.cOption);
          }
        });
    },

    // // 编辑页面地图 ---拿到区（Data）
    qzhandianfangfa(label, value) {
      this.qOption = []; //每次进来先清空区/县的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            res.result.forEach(item => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              };
              this.qOption.push(obj);
            });
          }
        });
    },
    // // 编辑页面地图 ---拿到街道（Data）
    jzhandianfangfa(label, value) {
      this.jOption = []; //每次进来先清空街道的Data源
      this.apis
        .allAddressList({
          name: label,
          code: value
        })
        .then(res => {
          if (res.code === 0) {
            console.log(res);
            // 增加判断，如果镇下面没有街道，就直接让街道变成空
            if (res.result.length !== 0) {
              res.result.forEach(item => {
                let obj = {
                  label: item.name,
                  value: item.adcode,
                  jingwei: item.center
                };
                this.jOption.push(obj);
              });
            } else {
              this.jOption = [];
            }
          }
        });
    },

    ExtractVideoFn() {
      const api = "https://h.aaaapp.cn/single_post"; //Battery_deposit.vue 单个帖子提取接口(如果主页批量提取Employ：https://h.aaaapp.cn/posts)
      const userId = "06A439846BD8D3435914A1BEBFE55C72"; //这里改成你自己的 userId
      const secretKey = "cd81457a97934f058ad55e374413ccd6"; //这里改成你自己的 secretKey
      let url = this.ExtractVideo;
      const params = {
        userId: userId,
        secretKey: secretKey,
        url: url
      };
      const xhr = new XMLHttpRequest();
      let _self = this;
      xhr.open("POST", api, true);
      xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          let res = JSON.parse(xhr.responseText);
          if (res.code == 200) {
            _self.title = res.data.text;
            _self.type = res.data.medias[0].media_type;
            _self.videoUrl = res.data.medias[0].resource_url;
            // console.log("视频地址", _self.videoUrl);
          } else {
            _self.$message({
              message: "提取Failure",
              type: "error"
            });
          }
        }
      };
      xhr.send(JSON.stringify(params));
    },

    videoUrlFn() {
      location.href = this.videoUrl;
    },
    openOperation() {
      // 点击多次显示与隐藏
      var currentTime = new Date().getTime();
      // 计算两次相连的点击时间间隔
      this.clickCount =
        currentTime - this.lastTime < this.waitTime ? this.clickCount + 1 : 1;
      this.lastTime = new Date().getTime();
      clearTimeout(this.clickTimer);
      this.clickTimer = setTimeout(() => {
        clearTimeout(this.clickTimer);
        // 处理点击事件
        // console.log(this.clickCount, "Frequency");
        if (this.clickCount > 6) {
          this.isExtractVideo = true;
        }
      }, this.waitTime + 10);
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;
}

#l-map {
  height: 250px;
  width: 100%;
}

#r-result {
  width: 100%;
}

.szddz {
  width: 130px;
}

.czddz {
  width: 130px;
}

.qzddz {
  width: 130px;
}

.jzddz {
  width: 130px;
}

.zhandiandiz {
  position: relative;
  top: -405px;
  left: 70px;
}

.zhandiandiz > span {
  margin-right: 10px;
}

#map {
  width: 100%;
  height: 500px;
}

.jingweip {
  margin-left: 80px;
  margin-bottom: 8px;
}
</style>
